// 按钮组显示隐藏切换按钮
const toggle = this.pageObj.getApiWidgetByAliasName('toggle');
// 弹窗 - 记录动态、一键会议、下发任务、协同会商、信息上报等。
const process = this.pageObj.getApiWidgetByAliasName('modal-process');
// Dev 系统环境变量
const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value;
// 三维组件
const widgetsGis = this.getApiPage().getApiWidgetByAliasName('三维组件')?.widgetObj;
// 路由参数
let params = this.pageObj.getVariables().find(v => v.name === "screen_params")?.value;
// 弹窗中的默认配置数据
const configs = process?.widgetObj.configs();
const Modal = process?.widgetObj.getModal();

if (params) {
  try {
    params = JSON.parse(params)
  } catch (e) {
  const { dataSource } = this.getApiPage().getApiWidgetByAliasName('judge-content')?.widgetObj._option || {};
    params = dataSource;
    console.error(e)
  }
}

// HTTP POST
const requestPost = (url, body, headers = {}) => {
  return fetch(url, {
    method: 'POST',
    headers: { "Content-Type": "application/json", ...headers },
    body: typeof body === 'object' ? JSON.stringify(body) : body,
  }).then(res => res.json())
};
// HTTP GET
const requestGet = (url) => {
  const headers = { "Content-Type": "application/json" };
  return fetch(url, { headers }).then(res => res.json())
};
console.log($event, configs);

// 一键会议
function callAllMembers () {
  const artemis = widgetsGis?.artemis;

  if (artemis && params?.id) {
    const headers = { "Content-type": "application/x-www-form-urlencoded" };
    const body = 'eventId=' + params.id;
    requestPost(`/${prefix}SummaryAssessmentSV/emergencyHandle/convergedCommunication`, body, headers).then(res => {
      if (res.success) {
        res.result.forEach(data => {
          data.userId = data.communicationAccount;
          data.username = data.communicationName;
          artemis.addMember(data);
        });

        artemis.createVideoMeeting();
      }
    })
  }
}

// 录像回放
function recordPlay () {
  // 回放组件
  const $playback = this.getApiPage().getApiWidgetByAliasName('playback');
  // 事件明细数据
  const { eventDetails } = params;

  if (eventDetails && Object.keys(eventDetails).length > 0) {
    const info = JSON.parse(eventDetails);
    widgetsGis.gisMap.setModalType('NONE');
    console.log('info', info);
    if (info.jpbPath) {
      $playback.widgetObj.setData([{ data: info.jpbPath }]);
      $playback.showWidget();
      $playback.widgetObj.render();
    } else {
      $playback.hideWidget();
      window.layer.msg('暂无录像回放')
    }
  } else {
    $playback.hideWidget();
    window.layer.msg('暂无录像回放')
  }
}

// 播放实时画面
function playing () {
  const { sourceDeviceId } = params;

  console.log('detailForm', detailForm);
  widgetsGis.gisMap.setModalType('NONE');

  if (sourceDeviceId) {
    const search = `?equipmentCode=${sourceDeviceId}`;
    // 打开实时视频
    requestGet(`/${prefix}Basics/basics-main/system/equipmentObject/listDetailByEquipmentCode${search}`)
      .then(({ success, result } = {}) => {
        console.log({ success, result });
        if (success && result) {
          const { rows } = result;
          const data = rows[0]?.equipmentConfig?.gbVideoConfig;
          var host = this.getApiPage().getVariables().find(x => x.name == "stream_url").value;
          widgetsGis.sullivan.close();
          if (data && data.sipUser && data.videoChannelId) {
            widgetsGis.sullivan.initial();
            widgetsGis.sullivan.addPlayer(`${host}/api/v1/stream/rtc/play`, `${data.sipUser}/${data.videoChannelId}`)
          } else {
            window.layer?.msg('暂无设备号/通道号')
          }
        }
      })
  }else {
    widgetsGis?.sullivan?.close();
    window.layer.msg('未关联摄像头');
  }
}

let config;
switch($event) {
  case '记录动态':
    config = configs['自定义内容']('记录动态');
    break;
  case '解除演练':
    config = configs['自定义内容']('提示：是否确定解除演练');
    break;
  case '结束演练':
    config = configs['自定义内容']('提示：是否确定结束演练');
    break;
  case '一键会议':
    callAllMembers ();
    break;
  case '实时画面':
    playing ();
    break;
  case '录像回放':
    recordPlay ();
    break;
  default:
    config = configs[$event]
}

if (config) {
  Modal.type = $event;
  process?.widgetObj.renderModal(config, { ...params, eventId: params.id, progress: 2 });
  process?.showWidget()
}

toggle?.widgetObj.toggle();

